import { createRouter, createWebHashHistory} from "vue-router";

import Login from '../view/login.vue'
import {ElMessage} from "element-plus";
import {jwtDecode} from "jwt-decode";
// import OperationForm from "@/view/form/operationForm.vue";
import UploadForm from "@/view/generalPage/uploadForm.vue";
import AddPerson from "@/view/managePage/addPerson.vue";
import CheckForm from "@/view/managePage/checkForm.vue";
import ResetPassword from "@/view/managePage/resetPassword.vue";
import ManagerHome from "@/view/managePage/managerHome.vue";
import GeneralHome from "@/view/generalPage/generalHome.vue";
import GetOwnAll from "@/view/generalPage/getOwnAll.vue";
import AllForm from "@/view/managePage/allForm.vue";
import ShowCharge from "@/view/charge/showCharge.vue";
import YesterdayAllChargeStation from "@/view/charge/yesterdayAllChargeStation.vue";
import ChargingScreen from "@/view/charge/ChargingScreen.vue";

const routes = [
    {path: '/', component: Login},
    {path:'/managerHome',component: ManagerHome},
    {path:'/generalHome',component: GeneralHome},
    // {path:'/operationOrder',component: OperationForm},
    {path:'/uploadForm',component: UploadForm},
    {path:'/addPerson',component: AddPerson},
    {path:'/checkForm',component: CheckForm},
    {path:'/resetPassword',component: ResetPassword},
    {path:'/getOwnAll',component: GetOwnAll},
    {path:'/allForm',component: AllForm},
    {path:'/showCharge',component: ShowCharge},
    {path:'/yesterdayAllChargeStation',component: YesterdayAllChargeStation},
    {path:'/chargingScreen',component: ChargingScreen},
]


const router = createRouter({
    history: createWebHashHistory(),
    routes,
})
/*
全局前置路由守卫，在路由发生改变之前执行操作
 */
// 路由守卫
function isValidToken(token) {
    try {
        jwtDecode(token);
        return true;
    } catch (error) {
        return false;
    }
}
router.beforeEach((to, from, next) => {
    // 获取token
    const token = localStorage.getItem('token');
    if (!token && to.path !== '/') {
        // 如果没有token且要跳转的不是登录页，则跳转到登录页
        ElMessage.error('请先登录！');
        next('/');
    } else if (token && !isValidToken(token)) {
        // 如果token无效，则跳转到登录页
        ElMessage.error('无效的token，请重新登录！');
        next('/');
    } else {
        next();
    }
});

// 导出，并在main.js中挂载到全局上
export default router